//
// File:	GuiPanel.cpp
// Author:	Thomas TISSOT-DUPONT
// E-mail:	<thomas.tissotdupont@free.fr>
// Create:	08/01/2010 00:30:50
// Purpose:	
//

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtGui/QPainter>
#include <QtGui/QStyleOption>
#include "GuiPanel.hpp"
#include "Trace.hpp"

//------------------------------------------------------------------
// Constructor / Destructor
//------------------------------------------------------------------
GuiPanel::GuiPanel(QWidget *pParent /* = NULL */)
	:	QWidget(pParent),
		m_lastValidSize(800, 600)
{
	SetStyleSheetFromFile("data/gui/styles.qss");
	resize(m_lastValidSize);
}

GuiPanel::~GuiPanel()
{
}

//------------------------------------------------------------------
// Update
//------------------------------------------------------------------
void GuiPanel::Update()
{
}

//------------------------------------------------------------------
// Style Sheet from File
//------------------------------------------------------------------
bool GuiPanel::SetStyleSheetFromFile(const std::string &filePath)
{
	QFile file(QString::fromStdString(filePath));
	if (file.open(QFile::ReadOnly | QFile::Text) == false)
		return false;
	QTextStream textStream(&file);
	QString styleCode = textStream.readAll();
	setStyleSheet(styleCode);
	return true;
}

//------------------------------------------------------------------
// Resize Event
//------------------------------------------------------------------
void GuiPanel::resizeEvent(QResizeEvent *e)
{
	//Ratio
	QSize oldSize = e->oldSize();
	QSize newSize = e->size();

	//Fix the size if the widget has just been shown (hide -> show)
	if (oldSize.width() <= 0 || oldSize.height() <= 0)
		oldSize = m_lastValidSize;

	//Move and resize the widgets
	if (oldSize.width() != -1 && oldSize.height() != -1)
	{
		QObjectList myChildrenList = children();
		QObjectList::iterator it = myChildrenList.begin();
		QObjectList::iterator ite = myChildrenList.end();
		for (; it != ite; ++it)
		{
			IGuiElement *pGuiElement = dynamic_cast<IGuiElement *>(*it);
			if (pGuiElement != NULL)
			{
				float flRatioWidth = static_cast<float>(newSize.width()) / static_cast<float>(oldSize.width());
				float flRatioHeight = static_cast<float>(newSize.height()) / static_cast<float>(oldSize.height());
				pGuiElement->repositionOnScreen(flRatioWidth, flRatioHeight);
			}
		}
	}
	m_lastValidSize = newSize;
	QWidget::resizeEvent(e);
}

//------------------------------------------------------------------
// Paint Event (required for CSS styles)
//------------------------------------------------------------------
void GuiPanel::paintEvent(QPaintEvent *e)
{
	QStyleOption option;
	option.init(this);
	QPainter painter(this);
	style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this);
	QWidget::paintEvent(e);
}
